/**
 * Created by winaya on 2016/10/17.
 */
$.fn.s_dropdown = function (configs) {
    var defaultConfig = {
        message: {
            noResults: '无符合条件的记录'
        },
        delay: {
            search: 400
        },
        forceSelection: false,
        onChange: function (value, text, $choice) {
            var $showInput = $(this).find($(this).dropdown("get").setting().selector.show);
            if ($showInput.length == 0) {
                return;
            }
            $showInput.val(text);
        },
        finish: function (module) {
            var $showInput = $(this).find(module.get.setting().selector.show);
            var $text = $(this).find(".text");
            if ($showInput && !$text.hasClass("default")) {
                $showInput.val($text.text());
            }
        },
        onShow: function () {
            var isScrollLoad, scrollLoadUrl;
            var _this = this;
            var $icon = $(this).find("i");
            $icon.hide();
            var $removeIcon = $(
                "<i class='dropdown fa-remove icon'></i>").insertAfter(
                $icon);
            $removeIcon.click(function () {
                $(this).parent().find("input:hidden").val("");
                $(this).parent().find("div.text").text("");
                $(this).parent().find("input.search").focus();
            });

            //实现从数据字典中当滚动到一定距离时分页加载数据
            // 配置项配置中当isScrollLoad为true,同时存在scrollLoadUrl请求地址时就会触发相应的滚动事件并进行数据请求加载
            $.each(configs, function (i, n) {
                if (n.key == $(_this).find("input[type=hidden]").attr("name")) {
                    isScrollLoad = n.isScrolLoad;
                    scrollLoadUrl = n.scrollLoadUrl;
                    return false;
                }
            });
            if (isScrollLoad) {
                var count = 1;
                var switchLoad = true;
                /*$(this).on("mousewheel", function (event) {
                 var scrollH = $(this).find(".menu")[0].scrollHeight;
                 var h = $(this).find(".menu").height();
                 var scrollTop = $(this).find(".menu").scrollTop();
                 console.log("scrollTop:" + scrollTop);
                 console.log("height:" + h);
                 console.log("scrollH:" + scrollH);
                 if (event.originalEvent.deltaY > 0 && (scrollH - scrollTop - h) < 50) {
                 console.log("产生滚动" + (++count));
                 var __this = this;
                 $.ajax({
                 url: scrollLoadUrl,
                 dataType: 'json',
                 type: 'post',
                 success: function (data) {
                 if (data.error_code == "0") {
                 console.log(data);
                 var html = "";
                 $.each(data.content, function (i, n) {
                 html +=
                 "<div class='item' data-value='" + n.dtKey
                 + "' data-text='" + n.dtValue + "'>("
                 + n.dtKey + ") " + n.dtValue + "</div>";
                 });
                 $(__this).find(".menu").append(html);
                 }
                 },
                 error: function (a, b, c) {
                 console.log(b);
                 }
                 });
                 }
                 });*/
                $(this).find(".menu").on("scroll", function (event) {
                    var scrollH = $(this)[0].scrollHeight;
                    var h = $(this).height();
                    var scrollTop = $(this).scrollTop();
                    if ((scrollH - scrollTop - h) < 50 && switchLoad) {
                        switchLoad = false;
                        console.log("触发了滚动的元素" + (++count));
                        var __this = this;
                        $.ajax({
                                   url: scrollLoadUrl,
                                   dataType: 'json',
                                   type: 'get',
                                   data: {"page": count, "pageSize": 15},
                                   success: function (data) {
                                       if (data.error_code == "0") {
                                           console.log(data);
                                           var html = "";
                                           $.each(data.content, function (i, n) {
                                               html +=
                                               "<div class='item' data-value='" + n.dtKey
                                               + "' data-text='" + n.dtValue + "'>("
                                               + n.dtKey + ") " + n.dtValue + "</div>";
                                           });
                                           $(__this).append(html);
                                           switchLoad = true;
                                       }
                                   },
                                   error: function (a, b, c) {
                                       console.log(b);
                                   }
                               });
                    }
                })
            }
        },
        onHide: function () {
            var $icons = $(this).find("i");
            $.each($icons, function (i, n) {
                if (i == 0) {
                    $(n).show();
                } else {
                    $(n).remove();
                }
            })

        },
        selector: {
            icon: '>.dropdown.icon:first',
            input: '> input[type="hidden"]:eq(0), > select',
            show: 'input[show]:eq(0)'
        }
    };
    var methods = {
        urlDataCall: function (config) {
            config = $.extend(true, {
                                  apiSettings: {
                                      onComplete: function (response, element, xhr) {
                                          var id = $(this).dropdown("get").id();
                                          var module = $.fn.dropdown.find(id);
                                          var all = module.get.setting().apiSettings.all;
                                          if (all) {
                                              $(this).dropdown();
                                              $(this).dropdown("set").menuData(
                                                  response[module.get.setting().fields.remoteValues]);
                                              if (config.afterSelected) {
                                                  $(this).dropdown("get").setting().afterSelected =
                                                  config.afterSelected;
                                              }
                                          }
                                          if (config.onComplete) {
                                              config.onComplete.call(this, response, element, xhr);
                                          }
                                      },
                                      onSuccess: function (response, element) {
                                          var id = $(this).dropdown("get").id();
                                          var module = $.fn.dropdown.find(id);
                                          var module_fields = module.get.setting().fields;
                                          module.remove.message();
                                          if (response.error_code == 0 && response.content.length) {
                                              var arr = [];
                                              for (var i = 0; i < response.content.length; i++) {
                                                  var obj = {};
                                                  obj.value = response.content[i].dtKey;
                                                  obj.text = response.content[i].dtValue;
                                                  obj.name =
                                                  "(" + response.content[i].dtKey + ")" + " "
                                                  + response.content[i].dtValue;
                                                  arr.push(obj);
                                              }
                                              response.success = "true";
                                              response.results = arr;

                                          }
                                          module.setup.menu({
                                                                values: response[module_fields.remoteValues]
                                                            });
                                          if (config.onRemoteQuerySuccess) {
                                              config.onRemoteQuerySuccess.call(this, response,
                                                                               element);
                                          }
                                          module.show();

                                      }
                                  }
                              },
                              {
                                  apiSettings: config.api
                              }, config);
            return config;
        },
        arrayDataCall: function (config) {
            var data = config.data;
            if (data == undefined || data.length == 0) {
                return;
            }
            if (config.dropdownDomType == "select") {
                $.each(data, function (i, n) {
                    config.dropdownSelector.append(
                        $("<option>").attr("data-value", n.code).text(n.name));
                });
            } else if (config.dropdownDomType == "div") {
                var $div = config.dropdownSelector;
                var $menu = $div.find(".menu");
                if ($menu.length == 0) {
                    $menu = $("<div class=\"menu\">");
                    $div.append($menu);
                }
                var html = "";
                $.each(data, function (i, n) {
                    html +=
                    "<div class='item' data-value='" + n.code + "' data-text='" + n.name + "'>("
                    + n.code + ") " + n.name + "</div>";
                    // html += $("<div class=\"item\">").attr("data-value", n.code)
                    //     .attr("data-text", n.name).text("(" + n.code + ") " + n.name).html();
                });
                $menu.append(html);
            }
            var model = $(config.key).dropdown();
            return config;
        },
        loadSelector: function (config) {
            var $select = $("select[name='" + config.key + "']");
            var $div = config.key.charAt(0) == "#" ? $("input" + config.key).parent() : $(
                "input[name='" + config.key + "']").parent();
            if ($select.length != 0) {
                config.dropdownSelector = $select;
                config.dropdownDomType = "select";
            } else if ($div) {
                config.dropdownSelector = $div;
                config.dropdownDomType = "div";
            }
        }
    };
    $.each(configs, function (i, n) {
        if (!n.data && !n.api) {
            console.error("无法初始化下拉框，原因为：数据配置为空，api配置项为空。key:" + n.key);
            return;
        }
        var config = n.api ? $.extend({}, defaultConfig, n, true) : $.extend({}, defaultConfig,
                                                                             {delay: {search: 20}},
                                                                             n, true);
        methods.loadSelector(config);
        if (config.api !== undefined) {
            config = methods.urlDataCall(config);
        } else {
            config = methods.arrayDataCall(config);
        }
        $(config.dropdownSelector).dropdown(config);
    });
};